package com.qiantu.phone.widget;

import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.Canvas;
import android.graphics.Paint;
import android.graphics.RectF;
import android.graphics.drawable.Drawable;
import android.util.AttributeSet;
import android.view.MotionEvent;
import android.view.SoundEffectConstants;
import android.view.View;

import com.qiantu.phone.R;
import com.qiantu.phone.app.AppApplication;

/**
 * 自定义评价星星类(任何形状)
 * yueleng  on 2017/1/9.
 */

public class StepView extends View {

    private float step = 0;
    private int stepNum = 3;
    private OnStepChangeListener changeListener;
    //是否可以点击
    private boolean isClick = true;
    //画笔
    private Paint mPaint;
    private int radius;
    private int horizontalSpacing;
    private int verticalDiff;
    private int stepWidth;
    private int stepHeight;
    private int firstHeight;
    private RectF lineRectF;
    private boolean isOnline = true;
    private float mTouchDownX;
    private float mTouchDownY;
    public int clickThreshold;//点击阈值
    public int moveThreshold;//滑动阈值
    private boolean isFirst;
    //有没有move
    private boolean hasMove;
    private long lastDownTime;

    public StepView(Context mContext, AttributeSet attrs) {
        super(mContext, attrs);
        init(mContext, attrs);
    }

    public StepView(Context mContext, AttributeSet attrs, int defStyleAttr) {
        super(mContext, attrs, defStyleAttr);
        init(mContext, attrs);
    }

    private void init(Context mContext, AttributeSet attrs) {
        //初始化控件属性
        setEnabled(isClick);
        radius = getResources().getDimensionPixelSize(R.dimen.dp_4);
        horizontalSpacing = getResources().getDimensionPixelSize(R.dimen.dp_4);
        //初始化画笔
        mPaint = new Paint();
        //设置抗锯齿
        mPaint.setAntiAlias(true);
//        mPaint.setShader(new BitmapShader(stepDrawDrawable, BitmapShader.TileMode.CLAMP, BitmapShader.TileMode.CLAMP));
        lineRectF = new RectF();
//        mDrawableLinearGradient = new LinearGradient(0, 0, 0, stepHeight, 0xffe8d2b1, 0xffd6ae7b, Shader.TileMode.CLAMP);
//        mBackgroundLinearGradient = new LinearGradient(0, 0, 0, stepHeight, 0xff151516, 0xff525252, Shader.TileMode.CLAMP);
        clickThreshold = getResources().getDimensionPixelSize(R.dimen.dp_2);
        moveThreshold = getResources().getDimensionPixelSize(R.dimen.dp_3);
    }

    @Override
    protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
        super.onMeasure(widthMeasureSpec, heightMeasureSpec);
        stepWidth = (getMeasuredWidth() - horizontalSpacing * (stepNum - 1)) / stepNum;
        stepHeight = getMeasuredHeight();
    }

    public void setStepNum(int stepNum) {
        this.stepNum = stepNum;
        invalidate();
    }

    @Override
    public void setEnabled(boolean enabled) {
        super.setEnabled(enabled);
        invalidate();
    }

    @Override
    protected void onDraw(Canvas canvas) {
        super.onDraw(canvas);
        if (!isOnline) {
            lineRectF.left = 0;
            lineRectF.top = 0;
            lineRectF.right = getWidth();
            lineRectF.bottom = stepHeight;
            mPaint.setColor(AppApplication.getInstance().getThemeColor(R.attr.secondaryColor8));
            canvas.drawRoundRect(lineRectF, radius, radius, mPaint);
            return;
        }
        for (int i = 0; i < stepNum; i++) {
            lineRectF.left = i * (stepWidth + horizontalSpacing);
            lineRectF.top = 0;
            lineRectF.right = lineRectF.left + stepWidth;
            lineRectF.bottom = stepHeight;
            mPaint.setColor(AppApplication.getInstance().getThemeColor(R.attr.secondaryColor8));
            canvas.drawRoundRect(lineRectF, radius, radius, mPaint);
        }
        for (int i = 0; i < step + 1; i++) {
            lineRectF.left = i * (stepWidth + horizontalSpacing);
            lineRectF.top = 0;
            lineRectF.right = lineRectF.left + stepWidth;
            lineRectF.bottom = stepHeight;
            mPaint.setColor(AppApplication.getInstance().getThemeColor(R.attr.themeColor));
            if (isEnabled()) {
                mPaint.setAlpha(255);
            } else {
//                mPaint.setColor(getResources().getColor(AppApplication.getInstance().getThemeColor(R.attr.secondaryColor4)));
                mPaint.setAlpha(51);
            }
            canvas.drawRoundRect(lineRectF, radius, radius, mPaint);
        }
    }

    @Override
    public boolean onTouchEvent(MotionEvent event) {
        if (!isEnabled() || !isOnline) {
            return true;
        }
        float x = 0;
        float y = 0;
        switch (event.getAction()) {
            case MotionEvent.ACTION_DOWN:
//                setMark(x*1.0f / (getMeasuredWidth()*1.0f/stepNum));
                mTouchDownX = event.getX();
                mTouchDownY = event.getY();
                lastDownTime = System.currentTimeMillis();
                isFirst = true;
                break;
            case MotionEvent.ACTION_MOVE:
                x = event.getX();
                y = event.getY();
                float distance = x - mTouchDownX;
                if ((Math.abs(distance) >= moveThreshold || hasMove)//第一次滑动距离达到一定一定距离
                        && System.currentTimeMillis() - lastDownTime > 150
//                        && (Math.abs(distance) >= mScaledTouchSlop || isOverTouchSlop)
                ) {
                    getParent().requestDisallowInterceptTouchEvent(true);
                    if (isFirst) {
                        isFirst = false;
                        setAlpha(0.8f);
                    }
                    hasMove = true;
                    updateStep(x, y);
                } else {
                    hasMove = false;
                }
                break;
            case MotionEvent.ACTION_UP:
                x = event.getX();
                y = event.getY();
                updateStep(x, y);
                if(changeListener != null){
                    playSoundEffect(SoundEffectConstants.CLICK);
                    changeListener.onStepChange(step);
                }
                setAlpha(1f);
                isFirst = false;
                hasMove = false;
                getParent().requestDisallowInterceptTouchEvent(false);
                break;
            case MotionEvent.ACTION_CANCEL:
                setAlpha(1f);
                isFirst = false;
                hasMove = false;
                getParent().requestDisallowInterceptTouchEvent(false);
                break;
        }
        return true;
    }

    private void updateStep(float x, float y){
        for (int i = 0; i < stepNum; i++) {
            lineRectF.left = i * (stepWidth + horizontalSpacing);
            lineRectF.right = lineRectF.left + stepWidth;
            if(i == stepNum - 1){
                lineRectF.right += horizontalSpacing;
            }
            if (lineRectF.left <= x && x <= lineRectF.right) {
                step = i;
                invalidate();
                break;
            }
        }
    }

    public void isOnline(boolean isOnline) {
        this.isOnline = isOnline;
        invalidate();
    }

    /**
     * 设置分数
     */
    public void setStep(Float step) {
        this.step = Math.round(step * 10) * 1.0f / 10;
        invalidate();
    }

    /**
     * 设置监听
     */
    public void setStepChangeLister(OnStepChangeListener stepChangeLister) {
        changeListener = stepChangeLister;
    }

    /**
     * 获取分数
     */
    public float getMark() {
        return step;
    }

    /**
     * 星星数量变化监听接口
     */
    public interface OnStepChangeListener {
        void onStepChange(float step);
    }

    /**
     * drawable转bitmap
     */
    private Bitmap drawableToBitmap(Drawable drawable) {
        if (drawable == null) return null;
        Bitmap bitmap = Bitmap.createBitmap(stepWidth, stepHeight, Bitmap.Config.ARGB_8888);
        Canvas canvas = new Canvas(bitmap);
        drawable.setBounds(0, 0, stepWidth, stepHeight);
        drawable.draw(canvas);
        return bitmap;
    }

}
